package com.example.share_doc.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.share_doc.controller.dto.UserPageDto;
import com.example.share_doc.entity.User;
import com.example.share_doc.mapper.UserMapper;
import com.example.share_doc.util.BusinessException;
import com.example.share_doc.util.ErrorEnum;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@AllArgsConstructor
@Slf4j
public class UserService {

    private UserMapper userMapper;

    public IPage userPage(UserPageDto userPageDto) {

        Page userPage = new Page(userPageDto.getPage(), userPageDto.getSize());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(userPageDto.getUserName())){
            queryWrapper.lambda().like(User::getUserName, userPageDto.getUserName());
        }
        if (StringUtils.isNotBlank(userPageDto.getPhone())){
            queryWrapper.lambda().like(User::getPhone, userPageDto.getPhone());
        }
        if (StringUtils.isNotBlank(userPageDto.getRoleName())){
            queryWrapper.lambda().like(User::getRoleName, userPageDto.getRoleName());
        }
        return userMapper.selectPage(userPage, queryWrapper);
    }

    public void userAdd(User user) {
        userMapper.insertOrUpdate(user);
    }

    public void userDeleteList(List<String> userIdList) {
        userMapper.deleteBatchIds(userIdList);
    }

    public User userLogin(User user) {
        String userName = user.getUserName();
        String password = user.getPassword();
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUserName, userName);
        queryWrapper.lambda().eq(User::getPassword, password);
        User result = userMapper.selectOne(queryWrapper);
        if (result==null){
            throw new BusinessException(ErrorEnum.LOGIN_ERROR);
        }
        return null;
    }
}
